import requests
from django.contrib.auth import login
from django.contrib.auth.models import User
from django.core.cache import cache
from django.shortcuts import redirect, reverse
from random import randint
from game.models.player.player import Player
from rest_framework_simplejwt.tokens import RefreshToken


def receive_code(request):
    data = request.GET
    code = data.get("code")
    state = data.get("state")

    if not cache.has_key(state):
        return redirect("index")
    cache.delete(state)

    apply_access_token_url = "https://www.acwing.com/third_party/api/oauth2/access_token/"
    params = {
        "appid": "624",
        "secret": "e414ba5bd3d74922ac2bdb8f40664db4",
        "code": code
    }

    access_token_res = requests.get(apply_access_token_url, params=params).json()
    access_token = access_token_res["access_token"]
    openid = access_token_res["openid"]

    players = Player.objects.filter(openid=openid)
    # 该用户已存在，无需重新获取信息，直接登录
    if players.exists():
        refresh = RefreshToken.for_user(players[0].user)
        # login(request, players[0].user)
        return redirect(reverse("index") + f"?access={str(refresh.access_token)}&refresh={str(refresh)}")

    get_userinfo_url = "https://www.acwing.com/third_party/api/meta/identity/getinfo/"
    params = {
        "access_token": access_token,
        "openid": openid,
    }
    userinfo_res = requests.get(get_userinfo_url, params=params).json()
    username = userinfo_res["username"]
    photo = userinfo_res["photo"]

    # 找到一个新的用户名
    while User.objects.filter(username=username).exists():
        username += str(randint(0, 9))
    user = User.objects.create(username=username)
    player = Player.objects.create(user=user, photo=photo, openid=openid)
    # login(request, user)
    refresh = RefreshToken.for_user(user)
    return redirect(reverse("index") + f"?access={str(refresh.access_token)}&refresh={str(refresh)}")

    # return redirect("index")
